package com.cps.frameauth.service;

import com.alibaba.fastjson.JSON;
import com.cps.frameauth.model.dto.JwtBody;
import com.cps.frameauth.model.entity.User;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 基础信息类
 *
 */
public interface BaseImpl {

  static HttpServletRequest getRequest() {
    ServletRequestAttributes requestAttributes =
        (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    return (requestAttributes == null) ? null : requestAttributes.getRequest();
  }

  /**
   * 获取用户信息
   *
   * @return
   */
  default User getUser() {
    JwtBody obj = (JwtBody) getRequest().getAttribute("user");
    User user = JSON.parseObject(JSON.toJSON(obj.getObject()).toString(), User.class);
    return user;
  }

  /**
   * 获取IP
   *
   * @return
   */
  default String getIp() {
    HttpServletRequest request = getRequest();
    if (request == null) {
      return "";
    }
    String ip = request.getHeader("X-Original-Forwarded-For");
    if (ip != null) {
      if (!ip.isEmpty() && !"unKnown".equalsIgnoreCase(ip)) {
        int index = ip.indexOf(",");
        if (index != -1) {
          return ip.substring(0, index);
        } else {
          return ip;
        }
      }
    }
    ip = request.getHeader("X-Forwarded-For");
    if (ip != null) {
      if (!ip.isEmpty() && !"unKnown".equalsIgnoreCase(ip)) {
        int index = ip.indexOf(",");
        if (index != -1) {
          return ip.substring(0, index);
        } else {
          return ip;
        }
      }
    }
    ip = request.getHeader("X-Real-IP");
    if (ip != null) {
      if (!ip.isEmpty() && !"unKnown".equalsIgnoreCase(ip)) {
        return ip;
      }
    }
    ip = request.getHeader("Proxy-Client-IP");
    if (ip != null) {
      if (!ip.isEmpty() && !"unKnown".equalsIgnoreCase(ip)) {
        return ip;
      }
    }
    ip = request.getHeader("WL-Proxy-Client-IP");
    if (ip != null) {
      if (!ip.isEmpty() && !"unKnown".equalsIgnoreCase(ip)) {
        return ip;
      }
    }
    ip = request.getRemoteAddr();
    return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
  }
}
